import axios from 'axios'
import { getToken, exitLogin } from '@/utils/app' //获取用户token
import { notification, message } from 'ant-design-vue'

import router from '../router/index' //使用路由直接引进来
import store from '@/store/index.js'

import { url } from '@/utils/options'

const http = axios.create({
  baseURL: url,
  timeout: 5000000
})
// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    // 配置请求头token内容
    if (getToken()) {
      config.headers['token'] = getToken()
    }
    // config.data = { method: "get", ...config.data };
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
http.interceptors.response.use(
  function (response) {
    // return Promise.resolve(false)
    // console.log(response, '请求结果是');
    if (response.status == 200) {
      const data = response.data
      if (data.success) {
        return Promise.resolve(data)
      } else {
        if (data.codeMsg) {
          notification.error({
            message: data.codeMsg.msg,
            duration: 2
          })
        } else {
          notification.error({
            message: '出错了！！'
          })
        }

        if (response.data.object) {
          return Promise.resolve(data)
        } else {
          return Promise.resolve(false)
        }
      }
    } else {
      return Promise.resolve(false)
    }
  },
  function (error) {
    console.log(error.response.status, '请求状态是')
    // 错误处理
    errorHandle(error)
    return Promise.resolve(false)
  }
)

// 错误处理
function errorHandle(error) {
  // 401登录过期-重新登录
  if (error.response.status == 401) {
    notification.warning({
      message: '登录过期、2s后跳转到登录页面',
      duration: 1
    })
    setTimeout(() => {
      exitLogin()
    }, 2000)

    return
  }
  if (error.response.status == 500) {
    notification.error({
      message: '服务器开小差了，请稍后再试~',
      duration: 2
    })
    return
  }
  if (error.response.status == 503) {
    notification.error({
      message: '服务器正在重启中，请稍后再试~',
      duration: 2
    })
    return
  }
  if (error.response.status == 404) {
    notification.error({
      message: '您访问的页面不存在哦~',
      duration: 2
    })
    return
  }
  notification.error({
    message: '服务器开小差了，请稍后再试~',
    duration: 2
  })
  return Promise.reject(error)
}
export default http
